<template>
    <main class="min-h-screen bg-base-100 p-4">
        <div class="max-w-4xl mx-auto">
            <!-- 页面标题 -->
            <div class="flex justify-between items-center mb-6">
                <div>
                    <h1 class="text-2xl font-bold text-base-content">
                        {{ isEdit ? "编辑联系人" : "新建联系人" }}
                    </h1>
                    <p class="text-sm text-gray-500 mt-1">
                        {{ isEdit ? "修改联系人信息" : "添加新的业务联系人" }}
                    </p>
                </div>
                <div class="flex gap-2">
                    <button
                        @click="$router.back()"
                        class="btn btn-outline btn-sm"
                    >
                        <svg
                            class="w-4 h-4"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                        >
                            <path
                                stroke-linecap="round"
                                stroke-linejoin="round"
                                stroke-width="2"
                                d="M10 19l-7-7m0 0l7-7m-7 7h18"
                            />
                        </svg>
                        返回
                    </button>
                </div>
            </div>

            <!-- 错误提示 -->
            <div v-if="error" class="alert alert-error mb-6">
                <svg
                    class="w-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                </svg>
                <span>{{ error }}</span>
            </div>

            <!-- 成功提示 -->
            <div v-if="successMessage" class="alert alert-success mb-6">
                <svg
                    class="w-5 h-5"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                >
                    <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                </svg>
                <span>{{ successMessage }}</span>
            </div>

            <!-- 表单区域 -->
            <div class="card bg-base-100 shadow-sm">
                <div class="card-body">
                    <form @submit.prevent="submitForm">
                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <!-- 左侧列 -->
                            <div class="space-y-4">
                                <!-- 姓名 -->
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >姓名
                                            <span class="text-error"
                                                >*</span
                                            ></span
                                        >
                                    </label>
                                    <input
                                        v-model="formData.name"
                                        type="text"
                                        placeholder="请输入联系人姓名"
                                        class="input input-bordered"
                                        :class="{ 'input-error': errors.name }"
                                        required
                                    />
                                    <label class="label" v-if="errors.name">
                                        <span
                                            class="label-text-alt text-error"
                                            >{{ errors.name }}</span
                                        >
                                    </label>
                                </div>

                                <!-- 所属公司 -->
                                <div class="form-control relative">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >所属公司</span
                                        >
                                    </label>
                                    <input
                                        v-model="companySearchText"
                                        type="text"
                                        placeholder="输入公司名称搜索..."
                                        class="input input-bordered"
                                        :class="{
                                            'input-error': errors.company_id,
                                        }"
                                        @input="handleCompanySearch"
                                        @focus="showCompanyDropdown = true"
                                        @blur="hideCompanyDropdown"
                                    />

                                    <!-- 下拉选择框 -->
                                    <div
                                        v-show="
                                            showCompanyDropdown &&
                                            filteredCompanies.length > 0 &&
                                            !companyLoading
                                        "
                                        class="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md border border-base-300 max-h-60 overflow-auto"
                                        style="top: 100%"
                                    >
                                        <div
                                            v-for="company in filteredCompanies"
                                            :key="company.id"
                                            class="px-4 py-2 hover:bg-base-200 cursor-pointer transition-colors"
                                            @mousedown="selectCompany(company)"
                                        >
                                            {{ company.name }}
                                        </div>
                                    </div>

                                    <!-- 加载状态 -->
                                    <div
                                        v-if="companyLoading"
                                        class="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md border border-base-300 p-4"
                                        style="top: 100%"
                                    >
                                        <span
                                            class="loading loading-spinner loading-sm text-primary"
                                        ></span>
                                        <span class="ml-2 text-sm"
                                            >搜索中...</span
                                        >
                                    </div>

                                    <!-- 空状态 -->
                                    <div
                                        v-if="
                                            showCompanyDropdown &&
                                            filteredCompanies.length === 0 &&
                                            !companyLoading &&
                                            companySearchText
                                        "
                                        class="absolute z-10 mt-1 w-full bg-white shadow-lg rounded-md border border-base-300 p-4"
                                        style="top: 100%"
                                    >
                                        <span class="text-sm text-gray-500"
                                            >未找到匹配的公司</span
                                        >
                                    </div>

                                    <label
                                        class="label"
                                        v-if="errors.company_id"
                                    >
                                        <span
                                            class="label-text-alt text-error"
                                            >{{ errors.company_id }}</span
                                        >
                                    </label>
                                </div>

                                <!-- 职位 -->
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >职位</span
                                        >
                                    </label>
                                    <input
                                        v-model="formData.job_title"
                                        type="text"
                                        placeholder="请输入职位"
                                        class="input input-bordered"
                                    />
                                </div>

                                <!-- 性别 -->
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >性别</span
                                        >
                                    </label>
                                    <select
                                        v-model="formData.gender"
                                        class="select select-bordered"
                                    >
                                        <option :value="undefined">
                                            请选择性别
                                        </option>
                                        <option value="0">男</option>
                                        <option value="1">女</option>
                                    </select>
                                </div>

                                <!-- 生日 -->
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >生日</span
                                        >
                                    </label>
                                    <input
                                        v-model="formData.birthday"
                                        type="date"
                                        class="input input-bordered"
                                    />
                                </div>
                            </div>

                            <!-- 右侧列 -->
                            <div class="space-y-4">
                                <!-- 电话 -->
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >电话
                                            <span class="text-error"
                                                >*</span
                                            ></span
                                        >
                                    </label>
                                    <input
                                        v-model="formData.phone"
                                        type="tel"
                                        placeholder="请输入电话号码"
                                        class="input input-bordered"
                                        :class="{ 'input-error': errors.phone }"
                                        required
                                    />
                                    <label class="label" v-if="errors.phone">
                                        <span
                                            class="label-text-alt text-error"
                                            >{{ errors.phone }}</span
                                        >
                                    </label>
                                </div>

                                <!-- 邮箱 -->
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >邮箱</span
                                        >
                                    </label>
                                    <input
                                        v-model="formData.email"
                                        type="email"
                                        placeholder="请输入邮箱地址"
                                        class="input input-bordered"
                                    />
                                </div>

                                <!-- 头像URL -->
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >头像URL</span
                                        >
                                    </label>
                                    <input
                                        v-model="formData.avatar"
                                        type="text"
                                        placeholder="请输入头像URL"
                                        class="input input-bordered"
                                    />
                                </div>

                                <!-- 状态 -->
                                <div class="form-control">
                                    <label class="label">
                                        <span class="label-text font-medium"
                                            >状态
                                            <span class="text-error"
                                                >*</span
                                            ></span
                                        >
                                    </label>
                                    <select
                                        v-model="formData.status"
                                        class="select select-bordered"
                                        :class="{
                                            'select-error': errors.status,
                                        }"
                                        required
                                    >
                                        <option value="" disabled>
                                            请选择状态
                                        </option>
                                        <option
                                            v-for="status in contactStatuses"
                                            :key="status.value"
                                            :value="status.value"
                                        >
                                            {{ status.label }}
                                        </option>
                                    </select>
                                    <label class="label" v-if="errors.status">
                                        <span
                                            class="label-text-alt text-error"
                                            >{{ errors.status }}</span
                                        >
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- 性格描述 -->
                        <div class="form-control mt-6">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >性格描述</span
                                >
                            </label>
                            <textarea
                                v-model="formData.personality"
                                class="textarea textarea-bordered h-24"
                                placeholder="请输入性格描述，便于客户管理或者对接工作，掌握喜好"
                            ></textarea>
                        </div>

                        <!-- 操作按钮 -->
                        <div
                            class="flex justify-end gap-3 mt-8 pt-6 border-t border-base-300"
                        >
                            <button
                                type="button"
                                @click="$router.back()"
                                class="btn btn-outline"
                                :disabled="loading"
                            >
                                取消
                            </button>
                            <button
                                type="submit"
                                class="btn btn-primary"
                                :disabled="loading"
                            >
                                <span
                                    v-if="loading"
                                    class="loading loading-spinner loading-sm"
                                ></span>
                                {{ isEdit ? "更新联系人" : "创建联系人" }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </main>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { invoke } from "@tauri-apps/api/core";

// 路由
const route = useRoute();
const router = useRouter();

// 联系人接口定义 - 根据后端Contact结构调整
interface Contact {
    id: number;
    name: string;
    email: string | null;
    phone: string | null;
    gender: number | null; // 0: 男, 1: 女
    birthday: string | null; // YYYY-MM-DD 格式
    job_title: string | null;
    avatar: string | null;
    company_id: number | null;
    status: number; // 0: 离职，1：在职，2：试用期，3：退休
    personality: string | null;
    company_name: string | null; // 新增：公司名称
    created_at: string;
    created_by: string;
    modified_at: string;
    modified_by: string;
}

// 公司接口定义
interface Company {
    id: number;
    name: string;
    type_id: number;
    status: number;
    address: string;
    staff_num: number;
    created_by: string;
    created_at: string;
    modified_by: string;
    modified_at: string;
}

// API响应接口
interface ApiResponse<T> {
    status_code: number;
    error_code: number;
    message: string;
    data: T | null;
}

// 响应式数据
const loading = ref(false);
const error = ref("");
const successMessage = ref("");

// 表单数据 - 根据数据库表结构调整
const formData = ref({
    name: "",
    email: null as string | null,
    phone: null as string | null,
    gender: null as number | null,
    birthday: null as string | null,
    job_title: null as string | null,
    avatar: null as string | null,
    company_id: null as number | null,
    status: 1, // 默认在职状态
    personality: null as string | null,
});

// 表单验证错误
const errors = ref({
    name: "",
    phone: "",
    status: "",
});

// 公司搜索相关数据
const companies = ref<Company[]>([]);
const companySearchText = ref("");
const showCompanyDropdown = ref(false);
const filteredCompanies = ref<Company[]>([]);
const companyLoading = ref(false);

// 防抖定时器
let searchDebounceTimer: NodeJS.Timeout | null = null;

// 联系人状态选项 - 根据数据库定义调整
const contactStatuses = [
    { value: 0, label: "离职" },
    { value: 1, label: "在职" },
    { value: 2, label: "试用期" },
    { value: 3, label: "退休" },
];

// 计算属性：判断是否为编辑模式
const isEdit = computed(() => {
    return route.params.id !== "New" && route.params.id !== undefined;
});

// 公司搜索处理（带防抖）
async function handleCompanySearch() {
    if (searchDebounceTimer) {
        clearTimeout(searchDebounceTimer);
    }

    searchDebounceTimer = setTimeout(async () => {
        const searchText = companySearchText.value.trim();

        if (searchText === "") {
            filteredCompanies.value = [];
            showCompanyDropdown.value = false;
            return;
        }

        companyLoading.value = true;
        showCompanyDropdown.value = true;

        try {
            // 调用后端API搜索公司
            const response: ApiResponse<Company[]> = await invoke(
                "list_company_by_name",
                { name: searchText },
            );

            if (response.status_code === 200 && response.data) {
                filteredCompanies.value = response.data;
            } else {
                console.error("搜索公司失败:", response.message);
                filteredCompanies.value = [];
            }
        } catch (err) {
            console.error("调用公司搜索API失败:", err);
            filteredCompanies.value = [];
            error.value = "搜索公司失败，请稍后重试";
        } finally {
            companyLoading.value = false;
        }
    }, 300);
}

// 选择公司
function selectCompany(company: Company) {
    formData.value.company_id = company.id;
    companySearchText.value = company.name;
    showCompanyDropdown.value = false;

    // 将选中的公司添加到公司列表中，以便后续查找
    if (!companies.value.find((c) => c.id === company.id)) {
        companies.value.push(company);
    }

    // 清除错误信息
    errors.value.company_id = "";
}

// 隐藏下拉框
function hideCompanyDropdown() {
    setTimeout(() => {
        showCompanyDropdown.value = false;
    }, 200);
}

// 表单验证
function validateForm(): boolean {
    let isValid = true;
    errors.value = { name: "", phone: "", status: "" };

    if (!formData.value.name.trim()) {
        errors.value.name = "请输入联系人姓名";
        isValid = false;
    }

    if (!formData.value.phone || !formData.value.phone.trim()) {
        errors.value.phone = "请输入电话号码";
        isValid = false;
    }

    if (formData.value.status === null || formData.value.status === undefined) {
        errors.value.status = "请选择联系人状态";
        isValid = false;
    }

    return isValid;
}

// 提交表单
async function submitForm() {
    if (!validateForm()) {
        return;
    }

    loading.value = true;
    error.value = "";
    successMessage.value = "";

    try {
        if (isEdit.value) {
            // 更新联系人
            await updateContact();
            successMessage.value = "联系人更新成功";
        } else {
            // 创建联系人
            await createContact();
            successMessage.value = "联系人创建成功";
        }

        // 成功后跳转回联系人列表或停留几秒后跳转
        setTimeout(() => {
            router.push({ name: "contacts" });
        }, 1500);
    } catch (err) {
        error.value = isEdit.value ? "更新联系人失败" : "创建联系人失败";
        console.error("提交表单失败:", err);
    } finally {
        loading.value = false;
    }
}

// 创建联系人
async function createContact() {
    try {
        // 准备API参数 - 转换为正确的类型
        const contactData = {
            id: 0,
            name: formData.value.name,
            email: formData.value.email,
            phone: formData.value.phone,
            gender:
                formData.value.gender !== null
                    ? parseInt(formData.value.gender as any)
                    : null,
            birthday: formData.value.birthday,
            job_title: formData.value.job_title,
            avatar: formData.value.avatar,
            company_id: formData.value.company_id,
            status: parseInt(formData.value.status as any),
            personality: formData.value.personality,
            created_by: "admin",
            modified_by: "admin",
        };

        console.log("创建联系人参数:", contactData);

        // 将contactData转换为JSON字符串
        const apiParams = {
            data: JSON.stringify(contactData),
        };

        // 调用后端API
        const response: ApiResponse<Contact> = await invoke(
            "create_contact",
            apiParams,
        );

        if (response.status_code !== 200) {
            throw new Error(response.message);
        }

        console.log("联系人创建成功:", response.data);
    } catch (err) {
        console.error("创建联系人失败:", err);
        throw err;
    }
}

// 更新联系人
async function updateContact() {
    try {
        const contactId = parseInt(route.params.id as string);

        // 准备API参数 - 转换为正确的类型
        const contactData = {
            id: contactId,
            name: formData.value.name,
            email: formData.value.email,
            phone: formData.value.phone,
            gender:
                formData.value.gender !== null
                    ? parseInt(formData.value.gender as any)
                    : null,
            birthday: formData.value.birthday,
            job_title: formData.value.job_title,
            avatar: formData.value.avatar,
            company_id: formData.value.company_id,
            status: parseInt(formData.value.status as any),
            personality: formData.value.personality,
            modified_by: "admin",
        };

        const apiParams = {
            data: JSON.stringify(contactData),
        };

        console.log("更新联系人参数:", apiParams);

        // 调用后端API
        const response: ApiResponse<Contact> = await invoke(
            "update_contact",
            apiParams,
        );

        if (response.status_code !== 200) {
            throw new Error(response.message);
        }

        console.log("联系人更新成功:", response.data);
    } catch (err) {
        console.error("更新联系人失败:", err);
        throw err;
    }
}

// 加载联系人数据（编辑模式下）
async function loadContact() {
    if (!isEdit.value) return;

    loading.value = true;
    try {
        const contactId = parseInt(route.params.id as string);

        // 调用后端API获取联系人详情
        const response: ApiResponse<Contact> = await invoke("contact_detail", {
            contact_id: contactId,
        });

        if (response.status_code === 200 && response.data) {
            const contact = response.data;

            // 填充表单数据
            formData.value = {
                name: contact.name,
                email: contact.email,
                phone: contact.phone,
                gender: contact.gender,
                birthday: contact.birthday
                    ? contact.birthday.split("T")[0]
                    : null, // 转换日期格式
                job_title: contact.job_title,
                avatar: contact.avatar,
                company_id: contact.company_id,
                status: contact.status,
                personality: contact.personality,
            };

            // 直接从contact中获取公司名称，不需要额外调用API
            if (contact.company_name) {
                companySearchText.value = contact.company_name;
            }
        } else {
            error.value = response.message || "加载联系人数据失败";
        }
    } catch (err) {
        error.value = "加载联系人数据失败";
        console.error("加载联系人数据失败:", err);
    } finally {
        loading.value = false;
    }
}

// 页面加载时初始化
onMounted(() => {
    loadContact();
});
</script>

<style scoped>
/* 确保表单元素对齐 */
.form-control {
    display: flex;
    flex-direction: column;
}

.label {
    padding: 0;
    margin-bottom: 0.5rem;
}

.label-text {
    font-weight: 500;
    color: #374151;
}

/* 响应式调整 */
@media (max-width: 1024px) {
    .grid {
        grid-template-columns: 1fr;
    }
}
</style>
